<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */
namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\Act;
use App\Model\ActAnswerJoin;
use App\Model\ActAnswerLog;
use App\Model\ActJoin;
use App\Model\ActPrizeGoods;
use App\Model\ActPrizeJoin;
use App\Model\ActRead;
use App\Model\ActSurveyLog;
use App\Model\ActSurveyQuestion;
use App\Model\Notify;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;
use Hyperf\DbConnection\Db;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]
class ActSurveyController extends AppBaseController
{

    /**
     * 获取本次问卷题库
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path:'surveyList/{act_id}',methods: 'get')]
    public function surveyList(int $act_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);

            if($info->type != 5) return $this->reMsg->re(0,'活动类型有误');

            //判断开始时间
            if($info->start_time && time()<strtotime($info->start_time)) return $this->reMsg->re(0,'活动未开始');
            //判断结束时间
            if($info->end_time && time()>strtotime($info->end_time)) return $this->reMsg->re(0,'活动已结束');
            //判断数量超出
            if($info->max_limit>0 && $info->join_count>=$info->max_limit) return $this->reMsg->re(0,'参与人数超过限制');

            $surveyJoinLog = ActSurveyLog::where(['act_id'=>$act_id,'uid'=>$_user->id])->first();

            if($surveyJoinLog){
                return $this->reMsg->re(10010,'已完成该问卷！');
            }
            //获取题目列表
            $questionList = ActSurveyQuestion::selectRaw('id,type')
                ->where(['act_id'=>$act_id,'status'=>1])
                ->get();

            $list = [];

            if($questionList->isNotEmpty()){
                //整理题库
                //题库id
                $questionIds = [];
                foreach($questionList as $key=>$value){
                    $questionIds[$key] = $value->id;
                }
                $list = ActSurveyQuestion::with(['answers'=>function($query){
                    $query->selectRaw('id,question_id,answer_title')->get();
                }])->whereIn('id',$questionIds)->get();
            }
            return $this->reMsg->re(1,'success',['list'=>$list]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 调研提交
     * @param int $act_id
     * @return object
     */
    #[RequestMapping(path: 'actSurveyJoin/{act_id}',methods: 'post,get')]
    public function actSurveyJoin(int $act_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            //抽奖活动信息
            $info = Act::where('id',$act_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            if($info->type != 5) return $this->reMsg->re(0,'活动类型有误');
            //判断开始时间
            if($info->start_time && time()<strtotime($info->start_time)) return $this->reMsg->re(0,'活动未开始');
            //判断结束时间
            if($info->end_time && time()>strtotime($info->end_time)) return $this->reMsg->re(0,'活动已结束');
            //判断参与人数
            if($info->max_limit>0 && $info->join_count>=$info->max_limit) return $this->reMsg->re(0,'参与人数超过限制');

            //先查询该用户是否已经参与抽奖
            $joinWhere['act_id'] = $act_id;
            $joinWhere['uid'] = $_user->id;
            $surveyJoinInfo = ActSurveyLog::where($joinWhere)->first();
            if($surveyJoinInfo) return $this->reMsg->re(10010);

            //获取数据
            $postData = $this->request->post('data', null);

            //虚拟数据
//            $postData = [
//                ['question_id'=>1, 'question_title'=>'11111','question_answer'=>'是是是'],
//                ['question_id'=>2, 'question_title'=>'22222','question_answer'=>'是是是'],
//            ];
            //虚拟数据

            if(empty($postData) || !is_array($postData)){
                return $this->reMsg->re(0,'答案数据丢失');
            }

            //调研记录
            $survey_log = [];

            foreach ($postData as $pKey=>$pVal){
                $survey_log[$pKey]['act_id'] = $info->id;
                $survey_log[$pKey]['uid'] = $_user->id;
                $survey_log[$pKey]['party_id'] = $_user->party_id;
                $survey_log[$pKey]['question_id'] = $pVal['question_id'];
                $survey_log[$pKey]['question_title'] = $pVal['question_title'];
                $survey_log[$pKey]['question_answer'] = $pVal['question_answer'];
                $survey_log[$pKey]['created_at'] = date('Y-m-d H:i:s',time());
            }

            //开启事务
            Db::beginTransaction();

            //记录调研过程
            Db::table('act_survey_log')->insert($survey_log);

            //往活动主参与记录里面加入记录
            $actJoinData['act_id'] = $info->id;
            $actJoinData['act_type'] = $info->type;
            $actJoinData['title'] = $info->title;
            $actJoinData['photo'] = $info->photo;
            $actJoinData['uid'] = $_user->id;
            $actJoinData['party_id'] = $_user->party_id;
            ActJoin::create($actJoinData);

            //加积分
            $params = [
                'type'=> 7, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                'action' => 1, //action 1:加积分 2:减积分
                'uid' => $_user->id,  //用户id
                'party_id' => $_user->party_id  //支部id
            ];
            $this->makeIntegralLog($params);

            Db::commit();
            return $this->reMsg->re(1,'success');
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }



}